package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.DimUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Set;

/**
 * Author: Felix
 * Date: 2021/12/28
 * Desc: 将维度侧输出流数据写到phoenix不同的维度表中
 */
public class DimSink extends RichSinkFunction<JSONObject> {

    private Connection conn;

    @Override
    public void open(Configuration parameters) throws Exception {
        //注册驱动
        Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
        //获取连接
        conn = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
    }

    @Override
    public void invoke(JSONObject jsonObj, Context context) throws Exception {
        String sinkTable = jsonObj.getString("sink_table");
        JSONObject dataJsonObj = jsonObj.getJSONObject("data");

        //拼接插入SQL
        String upsertSql = genUpsertSql(sinkTable, dataJsonObj);
        System.out.println("向Phoenix表中插入数据的SQL:" + upsertSql);

        //获取数据库操作对象
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(upsertSql);
            //执行SQL语句
            ps.executeUpdate();
            //注意：操作phoenix数据库的时候，默认自动提交设置的是false，我们需要手动提交
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("向Phoenix表中插入数据发生了异常");
        } finally {
            //释放资源
            if(ps != null){
                ps.close();
            }
        }

        //如果维度数据发生了变化，将Redis中缓存的维度数据给删除掉
        if(jsonObj.getString("type").equals("update")){
            DimUtil.deleteCached(sinkTable,jsonObj.getJSONObject("data").getString("id"));
        }
    }

    // 拼接upsert语句
    private String genUpsertSql(String sinkTable, JSONObject dataJsonObj) {
        Set<String> keys = dataJsonObj.keySet();
        Collection<Object> values = dataJsonObj.values();

        String upsertSql = "upsert into " + GmallConfig.HBASE_SCHEMA + "." + sinkTable
            + " (" + StringUtils.join(keys, ",") + ") " +
            "values('" + StringUtils.join(values, "','") + "')";
        return upsertSql;
    }
}
